package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.utils.FastDFSClient;
import com.changgou.file.utils.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author zwh
 * @Date 2019/9/23 20:44
 * @Version 1.0
 **/
@RestController
@RequestMapping("/file")
public class UploadFileController {

    @RequestMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        //获取文件全名
        String filename = file.getOriginalFilename();
        //判断文件名是否为空
        if (!StringUtils.isEmpty(filename)) {
            //获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1);
            //获取文件内容
            byte[] filenameBytes = file.getBytes();
            //创建上传文件的实体类
            FastDFSFile fastDFSFile = new FastDFSFile(filename, filenameBytes, ext);
            //文件上传
            String[] upload = FastDFSClient.upload(fastDFSFile);
            //拼接文件url地址
            String path = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];
            return new Result(true, StatusCode.OK, "上传成功", path);
        }
        return new Result(false, StatusCode.ERROR, "上传失败");
    }

}
